<?php

namespace App\Service;

use Exception;
use Hyperf\Context\ApplicationContext;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Filesystem\FilesystemFactory;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use League\Flysystem\FilesystemException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;
use function Hyperf\Support\env;

class UploadService
{
    #[Inject]
    protected RequestInterface $request;
    protected ContainerInterface $container;

    protected LoggerInterface $logger;

    public function __construct()
    {
        try {
            $this->container = ApplicationContext::getContainer();
            $this->logger = $this->container->get(LoggerFactory::class)->get('upload', 'default');
        } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) {
        }
    }

    /**
     * 上传图片
     * @throws Exception
     */
    public function image($file): array
    {
        if (is_null($file)) {
            throw new Exception('请选择图片');
        }
        if ($file->getSize() > env('UPLOAD_MAXSIZE')) {
            throw new Exception('上传的文件过大');
        }
        $ext = $file->getExtension();
        if (!in_array($ext, ['jpg', 'png', 'jpeg', 'gif'])) {
            throw new Exception('上传的格式不允许['.$ext.']');
        }
        $tmpFile = $file->getRealPath();
        $filename = date('Y/md/') . md5($tmpFile) . '.' . $ext;

        try {
            $cos = $this->container->get(FilesystemFactory::class)->get('cos');
            $cos->write('img/' . $filename, file_get_contents($tmpFile));
            return [
                'path' => $filename,
                'url' => img_url($filename),
            ];
        } catch (ContainerExceptionInterface|FilesystemException|NotFoundExceptionInterface $e) {
            $this->logger->warning('上传失败:' . $e->getMessage());
            throw new Exception('上传失败:' . $e->getMessage());
        }
    }
}